package logic

import (
	"context"
	"fmt"
	"shopping-mall/models"
	"shopping-mall/pkg"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *shopping_rpc.UserLoginRequest) (*shopping_rpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if in.Phone != "" {
		key := fmt.Sprintf("%s:%s", "login", in.Phone)
		get, _ := models.RDB.Get(models.Ctx, key).Result()
		if get != in.Code {
			return nil, fmt.Errorf("验证码错误")
		}
		if models.DB.Where("account = ?", in.Phone).Limit(1).Find(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return nil, fmt.Errorf("手机号未绑定账号")
		}
		models.RDB.Del(models.Ctx, key)
	} else {
		if models.DB.Where("account = ?", in.Account).Limit(1).Find(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return nil, fmt.Errorf("账号未注册")
		}
		if user.Password != pkg.MD5(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	}
	return &shopping_rpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
